<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Participant;
use App\Models\QuestionnaireOption;
use App\Models\QuestionnaireResult;
use App\Models\QuestionnaireTitle;
use App\Models\Survey;
use App\Org\Developer\Helper;
use App\Org\Developer\JsonReturnInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * @author  陈玉琦
 * 调查问卷
 */
class QuestionnaireController extends Controller
{
    private $fields = ['id', 'user_id', 'title', 'illustration', 'qrcode_image_url', 'type', 'start_time', 'end_time', 'direct_to'];

    /**
     * Display a listing of the resource.
     *
     * @return array
     */
    public function index(Request $request)
    {
        // 必须的用户 user_id
        // if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
        //     return JsonReturnInfo::ID_ERROR;
        // }

        // 调查 survey_id
        if (Helper::idInvalid($survey_id = $request->input('survey_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        try {
            // 必须存在且必须是用户自己的资源
            $surveyModel = Survey::select($this->fields)->where(['id' => $survey_id])->first();
            if (!(isset($surveyModel) && ($survey_id = $surveyModel->id))) {
                return JsonReturnInfo::infoFailure('要查询的调查投票不存在.');
            }
            // if (!Helper::isUserSelfResource($user_id, $surveyModel->user_id)) {
            //     return JsonReturnInfo::NOT_SELF_RESOURCE_ERROR;
            // }

            $questionnaireTitleData = QuestionnaireTitle::select(['id', 'title'])->where(['survey_id' => $survey_id])->get();
            foreach ($questionnaireTitleData as $key => $val) {
                $questionnaireTitleData[$key]['content'] = QuestionnaireOption::select(['id', 'name', 'image_url'])->where(['title_id' => $val['id']])->get();
            }
            $surveyModel['content'] = $questionnaireTitleData;
            return JsonReturnInfo::infoSuccess('调查问卷查询成功.', $surveyModel);
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function store(Request $request)
    {
        // 用户 user_id
        if (Helper::idInvalid($surveyData['user_id'] = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 生成二维码需要的前缀
        if (empty($qrcode_prefix = $request->input('qrcode_prefix', ''))) {
            return JsonReturnInfo::infoEmpty('qrcode_prefix');
        }

        // 调查的标题
        if (empty($surveyData['title'] = $request->input('title', ''))) {
            return JsonReturnInfo::infoEmpty('title');
        }

        // 调查问卷的说明
        if (empty($surveyData['illustration'] = $request->input('illustration', ''))) {
            return JsonReturnInfo::infoEmpty('illustration');
        }

        $surveyData['type'] = 'questionnaire';

        // 开始时间和结束时间
        $surveyData['start_time'] = $request->input('start_time', '');
        $surveyData['end_time'] = $request->input('end_time', '');
        if (empty($surveyData['start_time']) || empty($surveyData['end_time'])) {
            return JsonReturnInfo::infoEmpty('start_time 或 end_time');
        }
        // 开始时间必须早于结束时间
        if ($surveyData['start_time'] >= $surveyData['end_time']) {
            return JsonReturnInfo::START_TIME_GET_END_TIME_ERROR;
        }
        $surveyData['start_time'] = date('Y-m-d H:i:s', intval($surveyData['start_time'] / 1000) - 8 * 3600);
        $surveyData['end_time'] = date('Y-m-d H:i:s', intval($surveyData['end_time'] / 1000) - 8 * 3600);

        // 自定义跳转链接
        $surveyData['direct_to'] = $request->input('direct_to', '');

        try {
            $survey_id = 0;

            // 一个用户可以创建重复的调查，比如关于 xxx 的问卷，所以不必进行重复性校验。
            // 直接写入
            $createModel = Survey::create($surveyData);
            if (!(isset($createModel) && ($survey_id = $createModel->id))) {
                return JsonReturnInfo::infoFailure('调查问卷创建失败.');
            }

            // [{title:xxx, options:[{name:xxx,image_url:xxx}, {name:xxx,image_url:xxx}]}, 
            // {title:xxx, options:[{name:xxx,image_url:xxx}, {name:xxx,image_url:xxx}]}]
            // 写入问卷的数据，不管是单个还是多个，都是数组形式
            if (empty($content = $request->input('content', ''))) {
                return JsonReturnInfo::infoEmpty('content');
            }

            $content = json_decode($content, true);
            if (empty($content)) {
                return JsonReturnInfo::infoEmpty('content');
            }

            // 依次写入 title 表
            foreach ($content as $key => $val) {
                $createModel2 = QuestionnaireTitle::create([
                    'survey_id' => $survey_id,
                    'title' => $val['title']
                ]);
                if (!(isset($createModel2) && $createModel2->id)) {
                    return JsonReturnInfo::infoFailure('调查成功，问卷数据写入失败.');
                }

                // 批量写入数据库
                $batch = [];
                foreach ($val['options'] as $val2) {
                    $batch[] = [
                        'title_id' => $createModel2->id,
                        'name' => $val2['name'], 
                        'image_url' => $val2['image_url']
                    ];
                }
                $result = QuestionnaireOption::insert($batch);
                if (!$result) {
                    return JsonReturnInfo::infoFailure('调查成功，问卷数据写入失败.');
                }
            }

            // 需要生成二维码图片，将路径返回给 node
            $qrcodeImagePath = \App\Org\Developer\Helper::makeQrcodeImage($qrcode_prefix . $survey_id);

            $createModel->qrcode_image_url = $qrcodeImagePath;
            $createModel->save();
            
            return JsonReturnInfo::infoSuccess('调查问卷创建成功.', ['survey_id' => $survey_id, 'qrcode_image' => $qrcodeImagePath]);
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return array
     */
    public function update(Request $request, $id)
    {
        // 调查 survey_id 是否合法
        if (Helper::idInvalid($id)) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 用户 user_id
        if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 调查的标题
        if (empty($surveyData['title'] = $request->input('title', ''))) {
            return JsonReturnInfo::infoEmpty('title');
        }

        // 调查问卷的说明
        if (empty($surveyData['illustration'] = $request->input('illustration', ''))) {
            return JsonReturnInfo::infoEmpty('illustration');
        }

        $surveyData['type'] = 'questionnaire';

        // 生成二维码需要的前缀
        if (empty($qrcodePrefix = $request->input('qrcode_prefix', ''))) {
            return JsonReturnInfo::infoEmpty('qrcode_prefix');
        }

        // 开始时间和结束时间
        $surveyData['start_time'] = $request->input('start_time', '');
        $surveyData['end_time'] = $request->input('end_time', '');
        if (empty($surveyData['start_time']) || empty($surveyData['end_time'])) {
            return JsonReturnInfo::infoEmpty('start_time 或 end_time');
        }
        // 开始时间必须早于结束时间
        if ($surveyData['start_time'] >= $surveyData['end_time']) {
            return JsonReturnInfo::START_TIME_GET_END_TIME_ERROR;
        }
        $surveyData['start_time'] = date('Y-m-d H:i:s', intval($surveyData['start_time'] / 1000) - 8 * 3600);
        $surveyData['end_time'] = date('Y-m-d H:i:s', intval($surveyData['end_time'] / 1000) - 8 * 3600);

        // 自定义跳转链接
        $surveyData['direct_to'] = $request->input('direct_to', '');

        try {
            // 必须存在且必须是用户自己的资源
            $surveyModel = Survey::select($this->fields)->where(['id' => $id])->first();
            if (!(isset($surveyModel) && ($survey_id = $surveyModel->id))) {
                return JsonReturnInfo::infoFailure('要修改的调查问卷不存在.');
            }
            if (!Helper::isUserSelfResource($user_id, $surveyModel->user_id)) {
                return JsonReturnInfo::NOT_SELF_RESOURCE_ERROR;
            }

            $surveyModel->title = $surveyData['title'];
            $surveyModel->illustration = $surveyData['illustration'];
            $surveyModel->start_time = $surveyData['start_time'];
            $surveyModel->end_time = $surveyData['end_time'];
            $surveyModel->direct_to = $surveyData['direct_to'];

            $result = $surveyModel->save();
            if (!$result) {
                return JsonReturnInfo::infoFailure('调查问卷修改失败.');
            }

            // [{title:xxx, options:[{name:xxx,image_url:xxx}, {name:xxx,image_url:xxx}]},]
            // 写入问卷的数据，不管是单个还是多个，都是数组形式
            if (empty($content = $request->input('content', ''))) {
                return JsonReturnInfo::infoEmpty('content');
            }

            $content = json_decode($content, true);
            if (empty($content)) {
                return JsonReturnInfo::infoEmpty('content');
            }

            // 修改问卷的数据，不管是单个还是多个，都是数组形式
            // 但首先要把原来的问卷信息删除掉
            QuestionnaireOption::whereIn('title_id', function($query) use ($id) {
                $query->select('id')->from('questionnaire_titles')->where(['survey_id' => $id]);
            })->delete();
            QuestionnaireTitle::where(['survey_id' => $id])->delete();

            // 依次写入 title 表
            foreach ($content as $key => $val) {
                $updateModel = QuestionnaireTitle::create([
                    'survey_id' => $survey_id,
                    'title' => $val['title']
                ]);
                // 批量写入数据库
                $batch = [];
                foreach ($val['options'] as $val2) {
                    $batch[] = [
                        'title_id' => $updateModel->id, 
                        'name' => $val2['name'], 
                        'image_url' => $val2['image_url']
                    ];
                }
                $result = QuestionnaireOption::insert($batch);
                if (!$result) {
                    return JsonReturnInfo::infoFailure('调查修改成功，问卷数据修改失败.');
                }
            }
            return JsonReturnInfo::infoSuccess('调查问卷修改成功.');
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * 参与者调查结果反馈
     *
     * @return array
     */
    public function reply(Request $request)
    {
        // 调查 survey_id
        // 可以根据该值查询调查类型。如果没有传递该值，则需要传递调查类型，倒不如传递该值。
        if (Helper::idInvalid($survey_id = $request->input('survey_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        try {
            // 调查记录
            $surveyModel = Survey::select(['id', 'user_id', 'title', 'illustration', 'type'])->where(['id' => $survey_id])->first();
            if (!(isset($surveyModel) && $surveyModel->id)) {
                return JsonReturnInfo::infoFailure('该调查问卷不存在.');
            }

            // 反馈结果不能为空
            // [{title_id:xxx,option_id:xxx},{title_id:xxx,option_id:xxx},...] 都是单选
            if (empty($result = $request->input('result', ''))) {
                return JsonReturnInfo::infoEmpty('result');
            }

            $result = json_decode($result, true);
            if (empty($result)) {
                return JsonReturnInfo::infoEmpty('result');
            }

            $data = [];
            foreach ($result as $val) {
                $data[] = [
                    // 'participant_id' => $participant_id,
                    'title_id' => $val['title_id'],
                    'option_id' => $val['option_id']
                ];
            }

            $result = QuestionnaireResult::insert($data);
            if ($result) {
                return JsonReturnInfo::infoSuccess('反馈结果写入成功.');
            }
            return JsonReturnInfo::infoFailure('反馈结果写入失败.');
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * 调查投票/问卷结果下载
     * 应该是要每个主题的每个选项的被选择次数
     */
    public function download(Request $request)
    {
        // 用户 user_id
        if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 调查 survey_id
        if (Helper::idInvalid($survey_id = $request->input('survey_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 根据 questionnaire 的 id 查询调查的 survey_id，必须是用户自己的调查
        $surveyModel = Survey::select($this->fields)->where(['id' => $survey_id])->first();
        if (!(isset($surveyModel) && $surveyModel->id)) {
            return JsonReturnInfo::infoFailure('指定调查不存在.');
        }
        if (!Helper::isUserSelfResource($user_id, $surveyModel->user_id)) {
            return JsonReturnInfo::NOT_SELF_RESOURCE_ERROR;
        }

        // 根据 survey_id 找到所有问卷主题，每个主题有多个选项，每个选项对应一个 option_id，判断每个 option_id 中标次数
        $sql = "SELECT t.title,o.name,s.counts FROM 
   (SELECT option_id,COUNT(option_id) as counts FROM thearte_questionnaire_results WHERE option_id IN 
           (SELECT id FROM thearte_questionnaire_options WHERE title_id IN 
                   (SELECT id FROM thearte_questionnaire_titles WHERE survey_id = {$survey_id})) 
           GROUP BY option_id
   ) AS s 
LEFT JOIN thearte_questionnaire_options as o ON s.option_id = o.id 
LEFT JOIN thearte_questionnaire_titles t ON t.id = o.title_id 
ORDER BY t.id ASC,o.id ASC";

        $data = \Illuminate\Support\Facades\DB::select($sql);

        foreach ($data as $k => $item) {
            $data[$k] = json_decode(json_encode($item), true);
        }

        $title = [
            'title' => '投票主题',
            'option' => '选项',
            'option_total' => '次数'
        ];
        Helper::downloadExcel($data, $title, $surveyModel->title);// '调查问卷结果-' . DateHelper::dateTimeName()
    }
}
